// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-5glocnmp62950062'
})
const db = cloud.database()
const $ = db.command.aggregate
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID
  const dynamiclist = await db.collection('dynamiclist').aggregate().sort({
    time: -1
  }).lookup({
    from: 'loveList',
    let: {
      dynamic_id: '$_id'
    },
    pipeline: $.pipeline()
      .match(_.expr($.and([
        $.eq(['$dynamicid', '$$dynamic_id']),
        $.eq(['$openid', openid]),
        $.eq(['$status', true])
      ]))).done(),
    as: 'love'
  }).limit(4).end()
  const internlist = await db.collection('internlist').orderBy('date', 'desc').limit(3).get({
    success: (res) => {
      return res
    }
  })
  const tasklist = await db.collection('tasklist').aggregate().match({
    status: false,
  }).sort({
    date: -1
  }).lookup({
    from: 'applyTask',
    localField: '_id',
    foreignField: 'taskid',
    as: 'applyData'
  }).limit(3).end()


  return {
    dynamiclist,
    tasklist,
    internlist,
    event
  }
}